/**
 * 验证码API - 用于与后端验证码相关接口交互
 */
import api from './axios';
import { ApiResponse } from '../types/api';

/**
 * 验证码响应接口
 */
export interface CaptchaData {
  id: string;      // 验证码ID，用于后续验证
  imageUrl: string; // 验证码图片URL或Base64编码
  expiresAt?: number; // 验证码过期时间戳（可选）
}

/**
 * 获取验证码
 * 对应后端GET /adminapi/captcha路由
 * @returns 验证码数据，包含验证码ID和图片
 */
export const generateCaptcha = async (): Promise<CaptchaData> => {
  try {
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    const response = await api.get<ApiResponse<CaptchaData>>(`/captcha?t=${timestamp}`);
    
    if (response.data && response.data.code === 200 && response.data.data) {
      return response.data.data;
    } else {
      throw new Error(response.data.msg || '获取验证码失败');
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    throw error;
  }
};

/**
 * 验证验证码
 * 对应后端POST /adminapi/captcha/verify路由
 * @param captchaId 验证码ID
 * @param captchaCode 用户输入的验证码
 * @returns 验证结果
 */
export const verifyCaptcha = async (captchaId: string, captchaCode: string): Promise<boolean> => {
  try {
    const response = await api.post<ApiResponse<boolean>>('/captcha/verify', {
      captchaId,
      captchaCode
    });
    
    return response.data.code === 200;
  } catch (error) {
    console.error('验证码验证失败:', error);
    return false;
  }
};

export default {
  generateCaptcha,
  verifyCaptcha
};
